package com.ima.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CookieUtil {

    private static final Logger logger = LoggerFactory.getLogger(CookieUtil.class);

    /**
     * 设置cookie,自动过期(-1)
     * @param response
     * @param name
     * @param value
     */
    public static void addCookie(HttpServletResponse response, String name, String value) {
        addCookie(response, name,null, value, -1);
    }

    /**
     * 设置cookie,自动过期(-1)
     * @param response
     * @param name
     * @param domain
     * @param value
     */
    public static void addCookie(HttpServletResponse response, String name, String domain,String value) {
        addCookie(response, name, domain,value, -1);
    }

    /**
     * 设置cookie
     * @param response
     * @param name  cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期  以秒为单位
     */
    public static void addCookie(HttpServletResponse response, String name,String domain, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if(StringUtils.isNotBlank(domain)){
            cookie.setDomain(domain);
        }
        if (maxAge > 0) {
            cookie.setMaxAge(maxAge);
        }
        response.addCookie(cookie);
    }

    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = getCookieMap(request);
        return cookieMap.get(name);
    }


    /**
     * 删除Cookie，设置cooki立即过期
     * @param request
     * @param response
     * @param name
     */
    public static void delCookie(HttpServletRequest request,HttpServletResponse response, String name) {
        Cookie cookie = getCookie(request, name);
        if(cookie != null){
            cookie.setMaxAge(0);
            cookie.setValue(null);
            response.addCookie(cookie);
            logger.info("Clear cookie: {}",name);
        }
    }

    /**
     * 获取Cookie值
     * @param request
     * @param name cookie名字
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        if (cookie == null) {
            logger.info("No cookie, name:{}", name);
            return null;
        }
        try {
            logger.info("Get Cookie,name:{},value:{}", name, cookie.getValue());
            return cookie == null ? null : URLDecoder.decode(cookie.getValue(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return cookie.getValue();
        }
    }

    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private static Map<String, Cookie> getCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}
